package org.leetcode.middle.leetcode2;

public class Solution2
{

    public static void main(String[] args) {
        ListNode first = new ListNode();
        ListNode two = new ListNode();
        ListNode three = new ListNode();
        first.val=2;
        first.next=two;

        two.val=4;
        two.next=three;

        three.val=1;
        three.next=null;



        ListNode first1 = new ListNode();
        ListNode two1 = new ListNode();
        ListNode three1= new ListNode();


        first1.val=5;
        first1.next=two1;

        two1.val=3;
        two1.next=three1;

        three1.val=1;
        three1.next=null;

        ListNode listNode = addTwoNumbers(first, first1);

        String s = printNode(listNode);
        System.out.println(s);


    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode head1=l1;

        ListNode head2 = l2;
        while (head1!=null)
        {

            if (head2!=null)
            {
                head1.val += head2.val;
                head2=head2.next;
            }

            if (head1.next==null && head2!=null)
            {
                head1.next=head2;
                break;
            }

            head1=head1.next;

        }

        merge(l1);
        return l1;
    }


    public static void merge(ListNode head)
    {
        while (head!=null)
        {
            if (head.val>=10)
            {
                head.val= head.val-10;
                if (head.next==null)
                {
                    head.next=new ListNode(0);
                }
                head.next.val += 1;
            }

            head=head.next;
        }
    }

    public static String printNode(ListNode list)
    {
        String num =String.valueOf(list.val);
        while (list.next!=null)
        {
            String num2 = printNode(list.next);
            num=num+num2;
            break;
        }


        return num;

    }
}
